// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');

let fileStatus = new Set();
let myStatusBarItem;
const myCommandId = 'extension.readOnlyCode';
const myCommandIdOpen = 'extension.openFileWithReadOnlyCode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "ReadOnlyCode" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand(myCommandId, updateStatusBarItem);
	let disposable_open = vscode.commands.registerCommand(myCommandIdOpen, openFileWithReadOnlyCode);

	// create a new status bar item that we can now manage
	myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100);
    myStatusBarItem.command = myCommandId;
	context.subscriptions.push(myStatusBarItem);

	// register some listener that make sure the status bar 
	// item always up-to-date
	context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(readOnlyMode));
	context.subscriptions.push(vscode.workspace.onDidCloseTextDocument((e)=>{
        delReadOnlyMode(e.document);
        updateStatusBarItem();
    }));
    context.subscriptions.push(vscode.workspace.onDidChangeTextDocument(readOnlyMode));

	context.subscriptions.push(disposable);
	context.subscriptions.push(disposable_open);
}

function openFileWithReadOnlyCode(e) {
    vscode.workspace.openTextDocument(e.path).then((f) => {
        vscode.window.showTextDocument(f, 1, false).then(e => {
            console.log("openFileWithReadOnlyCode", e);
            addReadOnlyMode();
        });
    });
    // vscode.commands.executeCommand(myCommandId);
}


function readOnlyMode(e) {
    console.log("readOnlyMode function");
    if (!fileStatus.has(e.document)) {
        return;
    }
    // todo
    console.log("change file with read-only mode");

    // // 根据保存的数据
    // for(var i = 0; i < e.contentChanges.length; i++){
    //     const start = e.contentChanges[i].rangeOffset;
    //     const end = start + e.contentChanges[i].rangeLength;
    //     // console.log("change: ", e.contentChanges[i], fileStatus[e.document].slice(start, end));
    //     vscode.workspace.fs.writeFile(e.document.uri, fileStatus[e.document]);
    // }
    
    // 使用history恢复删除的文件
    vscode.commands.executeCommand("workbench.action.files.revert", e.document);

}


function updateStatusBarItem() {
    const f = vscode.window.activeTextEditor;
    console.log("updateStatusBarItem", f);
    if (f === undefined) {
        myStatusBarItem.hide();
        return;
    }

    if (!fileStatus.has(f.document)) {
        addReadOnlyMode(f.document);
	} else {
        delReadOnlyMode(f.document);
	}

}

function addReadOnlyMode(f) {
    myStatusBarItem.text =  `$(lock) ReadOnly`;
    myStatusBarItem.tooltip = "ReadOnly Mode";
    myStatusBarItem.show();

    console.log("add read only mode", f);
    if (fileStatus.has(f)) {
        return;
    }
    fileStatus.add(f);
    vscode.commands.executeCommand("workbench.action.files.save", f);
}

function delReadOnlyMode(f) {
    myStatusBarItem.text = `$(pencil) Edit`;
    myStatusBarItem.tooltip = "Edit Mode";
    myStatusBarItem.show();

    console.log("del read only mode", f);
    if (!fileStatus.has(f)) {
        return;
    }
    fileStatus.delete(f)
}

// this method is called when your extension is deactivated
function deactivate() {}

// eslint-disable-next-line no-undef
module.exports = {
	activate,
	deactivate
}